package com.ys.utils;

import com.ys.entity.Stu;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JWTUtils
 * @Author 1628994918qq.com
 * @Date 2023/2/28 20:39
 */
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTUtils {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.Expire}")
    private long expire;

    /**
     * 签发JWT
     */
    public String createJWT(Stu stu){
        Date date = new Date();
        Date expireDate = new Date(date.getTime() + expire);
        Map<String, Object> claims = new HashMap<>();
        claims.put("stuId",stu.getStuId());
        claims.put("stuPassword",stu.getStuPassword());
        String jwt = Jwts.builder()
                //设置装在内容
                .setClaims(claims)
                //签发时间
                .setIssuedAt(date)
                //过期时间
                .setExpiration(expireDate)
                //jwt主体   用来存放jwt的所有人  可以存放用户id或者角色id
                .setSubject(stu.getStuId())
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
        return jwt;
    }
    /**
     * 解析JWT
     */
    public Claims parseJWT(String jwt){
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt).getBody();
        return claims;
    }
}
